import LayerBase, { getLayerId } from "@/core/layers/base"
import { CanvasContextType } from "../public"


type Options = Pick<LayerImage, 'img' | 'name' | 'ctxType'> & 
Partial<Pick<LayerImage, 'x' | 'y' | 'zoom' | 'rotate' | 'width' | 'height' | 'naturalHeight' | 'naturalWidth' | 'aspectRatio' | 'opacity'>>

export default class LayerImage extends LayerBase {
  id = getLayerId()
  name: string
  ctxType: CanvasContextType
  readonly layerType = 'image'

  img: HTMLImageElement
  x: number
  y: number
  zoom: number
  rotate: number
  width: number
  height: number
  naturalHeight: number = 0
  naturalWidth: number = 0
  aspectRatio: number = 1

  constructor(options: Options){
    super()
    this.name = options.name
    this.ctxType = options.ctxType
    this.img = options.img
    this.x = options.x !== undefined ? options.x : 0
    this.y = options.y !== undefined ? options.y : 0
    this.zoom = options.zoom !== undefined ? options.zoom : 1
    this.rotate = options.rotate !== undefined ? options.rotate : 0
    this.width = options.width !== undefined ? options.width : 100
    this.height = options.height !== undefined ? options.height : 100
    if(options.img){
      this.naturalHeight = options.img.naturalHeight
      this.naturalWidth = options.img.naturalWidth
      this.aspectRatio = options.img.naturalWidth / options.img.naturalHeight
    }
  }

  render(ctx: CanvasRenderingContext2D){
    if(!this.offscreenCanvasCtx || this.height == 0 || this.width == 0) return false

    if(!this.rendered){
      this.offscreenCanvasCtx.canvas.width = this.naturalWidth
      this.offscreenCanvasCtx.canvas.height = this.naturalHeight
      this.offscreenCanvasCtx.beginPath()
      this.offscreenCanvasCtx.clearRect(0, 0, this.naturalWidth, this.naturalHeight)
      this.offscreenCanvasCtx.drawImage(this.img, 0, 0, this.naturalWidth, this.naturalHeight)
      this.rendered = true
    }

    ctx.globalAlpha = this.opacity
    ctx.drawImage(this.offscreenCanvasCtx.canvas, 0, 0, this.naturalWidth, this.naturalHeight, this.x, this.y, this.width, this.height)
    return false
  }

  serialize(){
    return {
      id: this.id,
      name: this.name,
      ctxType: this.ctxType,
      layerType: this.layerType,
      x: this.x,
      y: this.y,
      zoom: this.zoom,
      rotate: this.rotate,
      width: this.width,
      height: this.height,
      naturalHeight: this.naturalHeight,
      naturalWidth: this.naturalWidth,
      aspectRatio: this.aspectRatio,
      opacity: this.opacity,
      visible: this.visible,
    }
  }
}